package com.hr.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;


import java.sql.*;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class Basedao {
	private static ComboPooledDataSource dataSource = null;

	//获取配置文件
	static {
		try {
			//采用xml默认配置数据源
			dataSource = new ComboPooledDataSource();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//获取数据库对象
	public  static Connection getconn() {
		//从数据源直接获取连接
		Connection connection = null;
		try{
			connection = dataSource.getConnection();
		}catch(SQLException e){
			e.printStackTrace();
		}
		return connection;
	}

	//释放连接资源
	public void release(Connection con, Statement st, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void closeall(ResultSet rs, Statement ps, Connection conn){
		try {
			if(rs!=null)
				rs.close();
			if(ps!=null)
				ps.close();
			if(conn!=null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public static void close(Connection con, Statement statement){
		if (con!=null && statement != null){
			try {
				statement.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static int exectuIUD(String sql,Object[] params){
		int count=0;
		Connection conn=Basedao.getconn();
		PreparedStatement ps=null;
		try {
			ps=conn.prepareStatement(sql);
			if(params!=null){
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i+1, params[i]);
				}
			}
			count=ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			Basedao.closeall(null, ps, conn);
		}
		return count;
	}
}
